package org.jim.server.command.handler;

import org.apache.commons.lang3.StringUtils;
import org.jim.core.*;
import org.jim.core.exception.ImException;
import org.jim.server.JimServerAPI;
import org.jim.server.processor.group.GroupCmdProcessor;
import org.jim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jim.core.packets.AuthReqBody;
import org.jim.core.packets.Command;
import org.jim.core.packets.ExitGroupNotifyRespBody;
import org.jim.core.packets.Group;
import org.jim.core.packets.JoinGroupRespBody;
import org.jim.core.packets.JoinGroupResult;
import org.jim.core.packets.OutGroupReqBody;
import org.jim.core.packets.RespBody;
import org.jim.core.packets.User;
import org.jim.core.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;
import java.util.Objects;

/**
 * 
 * 版本: [1.0]
 * 功能说明: 加入群组消息cmd命令处理器
 * @author : WChao 创建时间: 2017年9月21日 下午3:33:23
 */
public class OutGroupReqHandler extends AbstractCmdHandler {
	
	private static Logger log = LoggerFactory.getLogger(OutGroupReqHandler.class);
	
	@Override
	public ImPacket handler(ImPacket packet, ImChannelContext channelContext) throws ImException {
		OutGroupReqBody outGroupReqBody = JsonKit.toBean(packet.getBody(), OutGroupReqBody.class);
		String groupId = outGroupReqBody.getGroupId();
		doAfterUnbind(channelContext, outGroupReqBody);
		RespBody respBody = null;
		if (JimServerAPI.unbindGroup(groupId, channelContext)) {
			respBody = new RespBody(Command.COMMAND_OUT_GROUP_RESP,ImStatus.C10023).setData(outGroupReqBody).setLocalId(outGroupReqBody.getLocalId());
		}else {
			respBody = new RespBody(Command.COMMAND_OUT_GROUP_RESP,ImStatus.C10024).setData(outGroupReqBody).setLocalId(outGroupReqBody.getLocalId());
		}
		return ProtocolManager.Converter.respPacket(respBody, channelContext);
		
	}
	
	public void doAfterUnbind(ImChannelContext imChannelContext, OutGroupReqBody outGroupReqBody) throws ImException {
		//发退出房间通知  COMMAND_EXIT_GROUP_NOTIFY_RESP
		ExitGroupNotifyRespBody exitGroupNotifyRespBody = new ExitGroupNotifyRespBody();
		exitGroupNotifyRespBody.setGroup(outGroupReqBody.getGroupId());
		User clientUser = imChannelContext.getSessionContext().getImClientNode().getUser();
		if(clientUser == null) {
			return;
		}
		User notifyUser = User.newBuilder().userId(clientUser.getUserId()).nick(clientUser.getNick()).build();
		exitGroupNotifyRespBody.setUser(notifyUser);
		RespBody respBody = new RespBody(Command.COMMAND_EXIT_GROUP_NOTIFY_RESP,exitGroupNotifyRespBody);
		ImPacket imPacket = new ImPacket(Command.COMMAND_EXIT_GROUP_NOTIFY_RESP, respBody.setLocalId(outGroupReqBody.getLocalId()).toByte());
		JimServerAPI.sendToGroup(outGroupReqBody.getGroupId(), imPacket);
	}
	
	@Override
	public Command command() {
		return Command.COMMAND_OUT_GROUP_REQ;
	}
}
